package com.excel.service.excel.v1;




import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.CommonEnum;
import com.corpgovernment.common.enums.PhoneCountryCodeEnum;
import com.corpgovernment.common.utils.ObjectStringTrimUtils;
import com.corpgovernment.costcenter.entity.db.MbOrgCostInfo;
import com.corpgovernment.costcenter.service.impl.CostCenterServiceImpl;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.SyncEmployeeCallBackRequestEntity;
import com.corpgovernment.organization.entity.SyncOrganizationRequestEntity;
import com.corpgovernment.organization.entity.db.*;
import com.corpgovernment.organization.enumm.*;
import com.corpgovernment.organization.service.IBdDeliveryBaseDataService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.util.ExcelUtils;
import com.corpgovernment.organization.util.StrUtils;
import com.corpgovernment.organization.vo.*;
import com.ctrip.corp.obt.generic.utils.*;
import com.excel.model.ExcelImportConfig;
import com.excel.qlexpress.ImportQlUtils;
import com.excel.qlexpress.OrgQlFunction;
import com.excel.service.excel.*;
import com.excel.util.ExcelImportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 组织
 *
 * @author hc
 */
@Service
@Slf4j
public class OrgAddProcessorV1<PREINSERT> implements ExcelImportProcessor<SyncEmployeeCallBackRequestEntity.FailInfo, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity, BizImportTask, PREINSERT> {

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private IOrganizationInfoService organizationInfoService;

    @Autowired
    private ExcelImportUtil excelImportUtil;

    @Autowired
    private IBdDeliveryBaseDataService bdDeliveryBaseDataService;

    @Autowired
    private CostCenterServiceImpl costCenterService;


    @Override
    public List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> assembleListFromExcel(BizImportTask task) {
        return null;
    }

    @Override
    public BizImportResult<SyncEmployeeCallBackRequestEntity.FailInfo,SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> assembleListFromExcel(BizImportTask task, MultipartFile file){

        BizImportResultImpl<SyncEmployeeCallBackRequestEntity.FailInfo,SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> result = new BizImportResultImpl<>();

        List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList = new ArrayList<>();
        List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> orgList = new ArrayList<>();

        // 获取excel资源
        XSSFWorkbook workBook = null;
        try {
            workBook = new XSSFWorkbook(file.getInputStream());
        } catch (IOException e) {
            log.error("上传异常", e);
            throw new CorpBusinessException(OrganizationResponseCodeEnum.FILE_WRONG_FORMAT);
        }
        String defaultBusinessCode = (String) task.getExt();
        MbImportExcelRecord record = (MbImportExcelRecord) task.getBasic();

        // excel输入
        List<OrgInfoExcelColumnVO> orgInfo = new ArrayList<>();
        List<OrgContactExcelColumnVO> orgContacts = new ArrayList<>();
        List<OrgInvoiceInfoExcelColumnVO> orgInvoice = new ArrayList<>();
        List<OrgDeliveryInfoExcelColumnVO> orgDelivery = new ArrayList<>();
        List<OrgConfigExcelColumnVO> orgConfigExcelColumnVOList = new ArrayList<>();
        List<PayTypeConfigExcelColumnVO> payTypeColumnList = new ArrayList<>();

        try {
            // excel输入
            orgInfo = getOrgInfoExcelColumnVOS( workBook, defaultBusinessCode);
            orgContacts = getOrgContanctInfoExcelColumnVOS(workBook);
            orgInvoice = getOrgInvoiceInfoExcelColumnVOS(workBook);
            orgDelivery = getOrgDeliveryInfoExcelColumnVOS(workBook);
            orgConfigExcelColumnVOList = getOrgConfigExcelColumnVOS(workBook);
            payTypeColumnList = getPayTypeConfigExcelColumnVOS(workBook);
        } catch (Exception e) {
            log.error("上传异常", e);
            throw new CorpBusinessException(OrganizationResponseCodeEnum.FILE_WRONG_FORMAT);
        }



        // 剔除空格
        orgInfo.forEach(t ->  ObjectStringTrimUtils.allFieldRemoveWarp(t));
        orgContacts.forEach(t ->  ObjectStringTrimUtils.allFieldRemoveWarp(t));
        orgInvoice.forEach(t ->  ObjectStringTrimUtils.allFieldRemoveWarp(t));
        orgDelivery.forEach(t ->  ObjectStringTrimUtils.allFieldRemoveWarp(t));
        orgConfigExcelColumnVOList.forEach(t ->  ObjectStringTrimUtils.allFieldRemoveWarp(t));
        payTypeColumnList.forEach(t ->  ObjectStringTrimUtils.allFieldRemoveWarp(t));

        // 组装成model对象
        Map<String, List<OrgInfoExcelColumnVO>> mapOrgInfo = Conditional.ofEmptyAble(orgInfo).orElse(new ArrayList<>()).stream()
                .filter(e -> Objects.nonNull(e) && !Objects.equals(e, new OrgInfoExcelColumnVO()) && StringUtils.isNotBlank(e.getBusinessCode()))
                .collect(Collectors.groupingBy(OrgInfoExcelColumnVO::getBusinessCode));
        Map<String, List<OrgContactExcelColumnVO>> mapOrgContacts = Conditional.ofEmptyAble(orgContacts).orElse(new ArrayList<>()).stream()
                .filter(e -> Objects.nonNull(e) && !Objects.equals(e, new OrgContactExcelColumnVO()) && StringUtils.isNotBlank(e.getBusinessCode()))
                .collect(Collectors.groupingBy(OrgContactExcelColumnVO::getBusinessCode));
        Map<String, List<OrgInvoiceInfoExcelColumnVO>> mapOrgInvoice = Conditional.ofEmptyAble(orgInvoice).orElse(new ArrayList<>()).stream()
                .filter(e -> Objects.nonNull(e) && !Objects.equals(e, new OrgInvoiceInfoExcelColumnVO()) && StringUtils.isNotBlank(e.getBusinessCode()))
                .collect(Collectors.groupingBy(OrgInvoiceInfoExcelColumnVO::getBusinessCode));
        Map<String, List<OrgDeliveryInfoExcelColumnVO>> mapOrgDelivery = Optional.ofNullable(orgDelivery).orElse(new ArrayList<>()).stream()
                .filter(e -> Objects.nonNull(e) && !Objects.equals(e, new OrgDeliveryInfoExcelColumnVO()) && StringUtils.isNotBlank(e.getBusinessCode()))
                .collect(Collectors.groupingBy(OrgDeliveryInfoExcelColumnVO::getBusinessCode));
        Map<String, List<OrgConfigExcelColumnVO>> mapOrgConfig = Optional.ofNullable(orgConfigExcelColumnVOList).orElse(new ArrayList<>()).stream()
                .filter(e -> Objects.nonNull(e) && !Objects.equals(e, new OrgConfigExcelColumnVO()) && StringUtils.isNotBlank(e.getBusinessCode()))
                .collect(Collectors.groupingBy(OrgConfigExcelColumnVO::getBusinessCode));
        Map<String, List<PayTypeConfigExcelColumnVO>> mapPayType = Optional.ofNullable(payTypeColumnList).orElse(new ArrayList<>()).stream()
                .filter(e -> Objects.nonNull(e) && !Objects.equals(e, new PayTypeConfigExcelColumnVO()) && StringUtils.isNotBlank(e.getBusinessCode()))
                .collect(Collectors.groupingBy(PayTypeConfigExcelColumnVO::getBusinessCode));

        orgInfo = this.sortOrgList(orgInfo);
        log.info("排序完之后的数据：{}", JsonUtils.toJsonString(orgInfo));
        List<OrgInfoExcelColumnVO> orgInfoExcelColumnVOS = orgInfo.stream().filter(Objects::nonNull).collect(Collectors.toList());

        //转换参数
        for (OrgInfoExcelColumnVO org : orgInfoExcelColumnVOS) {
            SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp = new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity();
            temp.setIsDelete(CommonEnum.Y.getDesc().equals(org.getIsDelete()));
            temp.setLineNo(org.getLineNo());
            // 塞入主体信息
            extractedBasic(org, temp);
            // 塞入联系人信息
            extractContacts(mapOrgContacts, org, temp);
            // 塞入发票信息
            extractInvoice(mapOrgInvoice, org, temp);
            // 塞入配送信息
            extractDelivery(mapOrgDelivery, org, temp);
            // 塞入组织配置
            extractOrgConfig(mapOrgConfig, org, temp);
            // 塞入配置信息
            extractPayType(mapPayType, org, temp);

            temp.setRecordId(record.getId());

            orgList.add(temp);
        }
        handleDeliveryAddress(orgList, mapOrgInfo, mapOrgDelivery);
        log.info("组织完全数据：{}", JsonUtils.toJsonString(orgList));

        // Excel 重复内容检查
        List<OrgInfoExcelColumnVO> uidDuplicates = OrgQlFunction.getDuplicateOrgField(orgInfo, OrgInfoExcelColumnVO::getBusinessCode); // 根据 组织编码 过滤重复数据
        for (OrgInfoExcelColumnVO item : uidDuplicates) {
            SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
            errorLog.setMainLineNo(item.getLineNo());
            errorLog.setLineNo(item.getLineNo());
            errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
            errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
            errorLog.setFailReason("Excel中存在相同组织编码");
            errorList.add(errorLog);
        }

        result.setErrorList(errorList);
        result.setDataList(orgList);
        return result;
    }



    @Override
    public BizImportResult<SyncEmployeeCallBackRequestEntity.FailInfo,SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> checkExcelData(List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> list) {

        BizImportResultImpl<SyncEmployeeCallBackRequestEntity.FailInfo,SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> result = new BizImportResultImpl<>();

        List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList = new ArrayList<>();
        List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> dataList = new ArrayList<>();

        // 通过qlexpress表达式校验数据内容
        for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item : list) {

            List<String> expressGroup = new ArrayList<>(Arrays.asList("组织编号","组织性质"));
            Map<String, String> failMsgMap = ImportQlUtils.getCheckFailMsg(ImportQlUtils.checkEmploy(expressGroup, ImportQlUtils.buildOrgCheckContextMap(item)));
            for (Map.Entry<String, String> entry : failMsgMap.entrySet()) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                String value = entry.getValue();
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setFailReason(value);
                errorList.add(errorLog);
            }

            // 联系人信息判断
            checkOrgContanct(errorList, item);

            // 发票信息
            checkOrgInvoic(errorList, item);

            // 配送地址
            checkOrgAddress(errorList, item);

            // 校验成本中心
            checkCostCenter(errorList, item);

            dataList.add(item);
        }
        dataList = dataList.stream().sorted(Comparator.comparing(t->Integer.valueOf(t.getLineNo()))).collect(Collectors.toList());
        result.setErrorList(errorList);
        result.setDataList(dataList);
        return result;
    }


    @Override
    public BizImportPreInsertResult<SyncEmployeeCallBackRequestEntity.FailInfo, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity, PREINSERT> checkDbDataWithPreInsert(List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> list) {


        BizImportPreInsertResultImpl<SyncEmployeeCallBackRequestEntity.FailInfo, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity, PREINSERT> result = new BizImportPreInsertResultImpl();

        List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList = new ArrayList<>();
        List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> dataList = new ArrayList<>();

        List<String> parentBusinessCodes = list.stream()
                .filter(o ->o.getBasicInfo() != null && StringUtils.isNotBlank(o.getBasicInfo().getParentBusinessCode()))
                .map(o -> o.getBasicInfo().getParentBusinessCode()).distinct().collect(Collectors.toList());


        List<String> needAddBusinessCodes = list.stream()
                .filter(o -> BooleanUtils.isNotTrue(o.getIsDelete()) && o.getBasicInfo() != null && StringUtils.isNotBlank(o.getBasicInfo().getBusinessCode()))
                .map(o -> o.getBasicInfo().getBusinessCode()).distinct().collect(Collectors.toList());

        List<String> needDelBusinessCodes = list.stream()
                .filter(o -> BooleanUtils.isTrue(o.getIsDelete()) && o.getBasicInfo() != null && StringUtils.isNotBlank(o.getBasicInfo().getBusinessCode()))
                .map(o -> o.getBasicInfo().getBusinessCode()).distinct().collect(Collectors.toList());

        Map<String, Boolean> addBusinessCodeMap = excelImportUtil.isExistByFieldInDb("mb_org_info","business_code",needAddBusinessCodes,true);

        Map<String, Boolean> delBusinessCodeMap = excelImportUtil.isExistByFieldInDb("mb_org_info","business_code",needDelBusinessCodes,true);

        Map<String, Boolean> parentBusinessCodeMap = excelImportUtil.isExistByFieldInDb("mb_org_info","business_code",parentBusinessCodes,true);

        // 填充父级组织编码，包含excel中的数据
        for (int i = 0; i < list.size(); i++) {
            parentBusinessCodeMap.put(list.get(i).getBasicInfo().getBusinessCode(),true);
        }

        // 需要新增的信息 暂无
        List<PREINSERT> needInsertList = new ArrayList<>();


        // 新增 校验db是否存在的组织编码
        for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item : list) {
            String itemBusinessCode = item.getBasicInfo().getBusinessCode();
            String itemParentBusinessCode = item.getBasicInfo().getParentBusinessCode();
            if(addBusinessCodeMap.containsKey(itemBusinessCode) && addBusinessCodeMap.get(itemBusinessCode)){
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setFailReason(ImportExcelRecordDetailLogErrorMessageEnum.SyncHumanResources_SyncOrgInfo_Business_Code_Is_Exist.getErrorMessage());
                errorList.add(errorLog);
            }

            if(delBusinessCodeMap.containsKey(itemBusinessCode) && !delBusinessCodeMap.get(itemBusinessCode)){
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setFailReason(ImportExcelRecordDetailLogErrorMessageEnum.SyncHumanResources_SyncOrgInfo_Business_Code_Is_Empty.getErrorMessage());
                errorList.add(errorLog);
            }

            if(parentBusinessCodeMap.containsKey(itemParentBusinessCode) && !parentBusinessCodeMap.get(itemParentBusinessCode)){
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setFailReason(ImportExcelRecordDetailLogErrorMessageEnum.A.getErrorMessage());
                errorList.add(errorLog);
            }

            checkDeliveryData(errorList, item);

            checkCostCenterData(errorList, item);

            dataList.add(item);
        }

        result.setErrorList(errorList);
        result.setDataList(dataList);
        result.setPreInsertList(needInsertList);
        return result;
    }

    @Override
    public void writeErrorLog(List<SyncEmployeeCallBackRequestEntity.FailInfo> mbImportExcelRecordDetailLogs, BizImportTask task) {

    }


    @Override
    public String getTag() {
        return "org_add_v1";
    }

    @Override
    public ExcelImportConfig getConfig() {
        ExcelImportConfig config = new ExcelImportConfig();
        config.setIsSharding(true);
        config.setIgnoreHeader(true);
        config.setRollBackType(1);
        return config;
    }


    public void checkCostCenterData(List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item) {
        String costCenterInfo = item.getBasicInfo().getCostCenterInfo();
        String type = item.getBasicInfo().getType();
        if (StringUtils.isBlank(costCenterInfo)) {
            return;
        }
        String bussinessCode = item.getBasicInfo().getBusinessCode();
        if (StringUtils.isNotBlank(item.getBasicInfo().getParentBusinessCode())) {
            bussinessCode = item.getBasicInfo().getParentBusinessCode();
        }
        MbOrgInfo thisItem = organizationInfoService.findByBusinessCode(bussinessCode);

        if(thisItem == null){
            return;
        }
        // 获取当前excel填写的组织编码 的最近一级的公司信息 -匹配职级
        MbOrgInfo companyOrgInfo = organizationInfoService.findFirstCompany(thisItem.getOrgId());

        Map<String, MbOrgCostInfo> costCenterCodeMap =
                costCenterService.costCenterCodeMapByCompany(companyOrgInfo.getOrgId());

        String[] costCenters = costCenterInfo.split(";");

        for (String costCenter : costCenters) {
            if (!costCenter.contains("/")) {
                continue;
            }
            String[] content = costCenter.split("/");
            if (content.length < 2) {
                continue;
            }

            MbOrgCostInfo mbOrgCostInfo = costCenterCodeMap.get(content[1]);
            if(OrgTypeEnum.D.getCode().equals(type)) {
                // 部门才校验成本中心必须存在
                if (null == mbOrgCostInfo) {
                    SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                    errorLog.setMainLineNo(item.getLineNo());
                    errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                    errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                    errorLog.setLineNo(item.getLineNo());
                    errorLog.setFailReason(OrganizationResponseCodeEnum.COST_CENTER_DONT_BELONG_COMPANY_ERROR.message());
                    errorList.add(errorLog);
                }
                if (mbOrgCostInfo!= null && !mbOrgCostInfo.getCostCenterName().equals(content[0])) {
                    SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                    errorLog.setMainLineNo(item.getLineNo());
                    errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                    errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                    errorLog.setLineNo(item.getLineNo());
                    errorLog.setFailReason(OrganizationResponseCodeEnum.COST_CENTER_NAME_ERROR.message());
                    errorList.add(errorLog);
                }
            } else if(mbOrgCostInfo != null) {
                if (!mbOrgCostInfo.getCostCenterName().equals(content[0])) {
                    SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                    errorLog.setMainLineNo(item.getLineNo());
                    errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                    errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                    errorLog.setLineNo(item.getLineNo());
                    errorLog.setFailReason(OrganizationResponseCodeEnum.COST_CENTER_NAME_ERROR.message());
                    errorList.add(errorLog);
                }
            }
        }

    }

    public void checkDeliveryData(List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item) {
        if(CollectionUtils.isEmpty(item.getDeliveryAddressList())){
            return;
        }
        item.getDeliveryAddressList().forEach(a -> {
            BdDeliveryBaseData provide = bdDeliveryBaseDataService.queryByNameLike(a.getProvinceName(), DeliveryBaseDataTypeEnum.P.name());
            if (provide != null && (provide.getName().equals(a.getProvinceName()) || (provide.getName().length() - a.getProvinceName().length() == 1 && (provide.getName().substring(provide.getName().length() - 1).equals("省")
                    || provide.getName().substring(provide.getName().length() - 1).equals("市"))))) {
                a.setProvinceCode(provide.getCode());
            }else{
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setLineNo(a.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.DELIVERY.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.DELIVERY.getIndex());
                errorLog.setFailReason(String.format(OrganizationResponseCodeEnum.DELIVERY_MAPPING_FAILED.message(), a.getProvinceName()));
                errorList.add(errorLog);
            }
            BdDeliveryBaseData city = bdDeliveryBaseDataService.queryByNameLike(a.getCityName(), DeliveryBaseDataTypeEnum.C.name());
            if (city != null && (city.getName().equals(a.getCityName()) || (city.getName().length() - a.getCityName().length() == 1 && city.getName().substring(city.getName().length() - 1).equals("市")
            ))) {
                a.setCityCode(city.getCode());
            }else{
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setLineNo(a.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.DELIVERY.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.DELIVERY.getIndex());
                errorLog.setFailReason(String.format(OrganizationResponseCodeEnum.DELIVERY_MAPPING_FAILED.message(), a.getCityName()));
                errorList.add(errorLog);
            }
            BdDeliveryBaseData area = bdDeliveryBaseDataService.queryByNameLike(a.getDistrictName(), DeliveryBaseDataTypeEnum.A.name());
            if (area != null && (area.getName().equals(a.getDistrictName()) || (area.getName().length() - a.getDistrictName().length() == 1 && (area.getName().substring(area.getName().length() - 1).equals("区")
                    || area.getName().substring(area.getName().length() - 1).equals("县"))))) {
                a.setDistrictCode(area.getCode());
            }else {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setLineNo(a.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.DELIVERY.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.DELIVERY.getIndex());
                errorLog.setFailReason(String.format(OrganizationResponseCodeEnum.DELIVERY_MAPPING_FAILED.message(), a.getDistrictName()));
                errorList.add(errorLog);
            }
        });
    }


    public void checkCostCenter(List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item) {
        String costCenterInfo = item.getBasicInfo().getCostCenterInfo();
        String costCenterInfoDefault = item.getBasicInfo().getCostCenterInfoDefault();
        if (StringUtils.isBlank(costCenterInfo) && StringUtils.isBlank(costCenterInfoDefault)) {
            return;
        }

        if(StringUtils.isNotBlank(costCenterInfoDefault)) {
            if(StringUtils.isBlank(costCenterInfo)) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_Failure.getErrorMessage());
                errorList.add(errorLog);
                return;
            }
            if(! costCenterInfoDefault.contains("/")) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_ERROR.getErrorMessage());
                errorList.add(errorLog);
                return;
            }
            if( costCenterInfoDefault.split("/").length != 2) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_More.getErrorMessage());
                errorList.add(errorLog);
                return;
            }

            Boolean flag = true;
            String[] costCenters = costCenterInfo.split(";");
            for (String costCenter : costCenters) {
                if(StringUtils.equals( costCenterInfoDefault, costCenter, false)) {
                    flag = false;
                }
            }
            if(flag) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.INFO.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.INFO.getIndex());
                errorLog.setLineNo(item.getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_Failure.getErrorMessage());
                errorList.add(errorLog);
            }
        }

    }


    private void checkOrgAddress(List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item) {
        if (CollectionUtils.isNotEmpty(item.getDeliveryAddressList())) {
            for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.DeliveryAddressEntity address : item.getDeliveryAddressList()) {
                // 空值判断
                if (address != null && (StringUtils.isEmpty(address.getProvinceName()) || StringUtils.isEmpty(address.getCityName())
                        || StringUtils.isEmpty(address.getDistrictName()) || StringUtils.isEmpty(address.getAddress())
                        || StringUtils.isEmpty(address.getRecipientName()) || StringUtils.isEmpty(address.getRecipientPhone()))) {
                    log.error("checkOrganizationRequest org.getDeliveryAddressList() 空值判断");
                    SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                    errorLog.setMainLineNo(item.getLineNo());
                    errorLog.setSheetName(OrgInfoSheetEnum.DELIVERY.getName());
                    errorLog.setSheetIndex(OrgInfoSheetEnum.DELIVERY.getIndex());
                    errorLog.setLineNo(address.getLineNo());
                    errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyDeliveryInfo_Failure.getErrorMessage());
                    errorList.add(errorLog);
                }
                if (address != null) {
                    // 默认不是默认配送地址
                    address.setIsDefault(Optional.ofNullable(address.getIsDefault()).orElse(false));
                    PhoneCountryCodeEnum phoneCountryCodeEnum = StringUtils.isEmpty(address.getRecipientCountryCode()) ? null : PhoneCountryCodeEnum.getByCountryCode(address.getRecipientCountryCode());
                    if (phoneCountryCodeEnum == null) {
                        // 默认中国大陆
                        address.setRecipientCountryCode(PhoneCountryCodeEnum.CN.getCountryCode());
                    }
                    if (!StringUtils.isEmpty(address.getPostCode()) && !address.getPostCode().matches("^[0-9]\\d{5}$")) {
                        SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                        errorLog.setMainLineNo(item.getLineNo());
                        errorLog.setSheetName(OrgInfoSheetEnum.DELIVERY.getName());
                        errorLog.setSheetIndex(OrgInfoSheetEnum.DELIVERY.getIndex());
                        errorLog.setLineNo(address.getLineNo());
                        errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_DeliveryAddress_PostCodeFormat_Failure.getErrorMessage());
                        errorList.add(errorLog);
                    }
                    Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
                    if (!StringUtils.isEmpty(address.getRecipientPhone()) && !p.matcher(address.getRecipientPhone()).find()) {
                        SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                        errorLog.setMainLineNo(item.getLineNo());
                        errorLog.setSheetName(OrgInfoSheetEnum.DELIVERY.getName());
                        errorLog.setSheetIndex(OrgInfoSheetEnum.DELIVERY.getIndex());
                        errorLog.setLineNo(address.getLineNo());
                        errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_DeliveryAddress_PhoneFormat_Failure.getErrorMessage());
                        errorList.add(errorLog);
                    }
                }
            }
        }
    }

    private void checkOrgInvoic(List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item) {
        if (CollectionUtils.isNotEmpty(item.getInvoiceList())) {

            for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.InvoiceInfoEntity invoice : item.getInvoiceList()) {

                // 只有公司才能关联发票
                if (!OrgTypeEnum.C.getCode().equals(item.getBasicInfo().getType())) {
                    log.error("checkOrganizationRequest 只有公司才能关联发票，删除发票");
                    SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                    errorLog.setMainLineNo(item.getLineNo());
                    errorLog.setSheetName(OrgInfoSheetEnum.INVOICE.getName());
                    errorLog.setSheetIndex(OrgInfoSheetEnum.INVOICE.getIndex());
                    errorLog.setLineNo(invoice.getLineNo());
                    errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_InvoiceButNotCompany_Failure.getErrorMessage());
                    errorList.add(errorLog);
                }

                // 空值判断
                if (invoice != null && (StringUtils.isEmpty(invoice.getInvoiceTitle()) || StringUtils.isEmpty(invoice.getTaxId())
                        || StringUtils.isEmpty(invoice.getAccountBank()) || StringUtils.isEmpty(invoice.getAccountCardNo())
                        || StringUtils.isEmpty(invoice.getCorporationPhone()) || StringUtils.isEmpty(invoice.getCorporationAddress()))) {
                    log.error("checkOrganizationRequest org.getInvoiceTitle() 空值判断");
                    SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                    errorLog.setMainLineNo(item.getLineNo());
                    errorLog.setSheetName(OrgInfoSheetEnum.INVOICE.getName());
                    errorLog.setSheetIndex(OrgInfoSheetEnum.INVOICE.getIndex());
                    errorLog.setLineNo(invoice.getLineNo());
                    errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyInvoiceInfo_Failure.getErrorMessage());
                    errorList.add(errorLog);
                }
            }
        }
    }

    private void checkOrgContanct(List<SyncEmployeeCallBackRequestEntity.FailInfo> errorList, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity item) {
        if (item.getContactInfo() != null) {
            PhoneCountryCodeEnum phoneCountryCodeEnum = StringUtils.isEmpty(item.getContactInfo().getContactCountryCode()) ? PhoneCountryCodeEnum.CN : PhoneCountryCodeEnum.getByCountryCode(item.getContactInfo().getContactCountryCode());
            if (phoneCountryCodeEnum == null) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.CONTANCT.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.CONTANCT.getIndex());
                errorLog.setLineNo(item.getContactInfo().getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_CountryCodeFormat_Failure.getErrorMessage());
                errorList.add(errorLog);
            }
            if (!StringUtils.isEmpty(item.getContactInfo().getContactEmail()) && !item.getContactInfo().getContactEmail().matches("^[A-Za-z0-9\\-_]+[A-Za-z0-9\\.\\-_]*[A-Za-z0-9\\-_]+@[A-Za-z0-9]+[A-Za-z0-9\\.\\-_]*(\\.[A-Za-z0-9\\.\\-_]+)*[A-Za-z0-9]+\\.[A-Za-z0-9]+[A-Za-z0-9\\.\\-_]*[A-Za-z0-9]+$")) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.CONTANCT.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.CONTANCT.getIndex());
                errorLog.setLineNo(item.getContactInfo().getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_EmailFormat_Failure.getErrorMessage());
                errorList.add(errorLog);
            }
            Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
            if (!StringUtils.isEmpty(item.getContactInfo().getContactPhone()) && !p.matcher(item.getContactInfo().getContactPhone()).find()) {
                SyncEmployeeCallBackRequestEntity.FailInfo errorLog = new SyncEmployeeCallBackRequestEntity.FailInfo();
                errorLog.setMainLineNo(item.getLineNo());
                errorLog.setSheetName(OrgInfoSheetEnum.CONTANCT.getName());
                errorLog.setSheetIndex(OrgInfoSheetEnum.CONTANCT.getIndex());
                errorLog.setLineNo(item.getContactInfo().getLineNo());
                errorLog.setFailReason(ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_PhoneFormat_Failure.getErrorMessage());
                errorList.add(errorLog);
            }
        }
    }


    private void extractedBasic(OrgInfoExcelColumnVO org, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp) {
        SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.BasicInfoEntity basic = new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.BasicInfoEntity();
        basic.setOrgId(org.getOrgId());
        basic.setName(org.getName());
        basic.setType(OrgTypeEnum.D.getDesc().equals(org.getType()) ? OrgTypeEnum.D.getCode() : OrgTypeEnum.C.getCode());
        basic.setParentOrgId(org.getParentOrgId());
        basic.setIsActive(!CommonEnum.N.getDesc().equals(org.getIsActive()));
        basic.setBusinessCode(org.getBusinessCode());
        basic.setParentBusinessCode(org.getParentBusinessCode());
        basic.setCostCenterInfo(org.getCostCenterInfo());
        basic.setCostCenterInfoDefault(org.getCostCenterInfoDefault());
        basic.setLineNo(temp.getLineNo());
        basic.setMainLineNo(temp.getLineNo());
        log.info("基础信息：" + JsonUtils.toJsonString(basic));
        temp.setBasicInfo(basic);
    }


    private List<OrgInfoExcelColumnVO> getOrgInfoExcelColumnVOS(XSSFWorkbook sheets, String defaultBusinessCode){
        XSSFSheet sheetOrg = sheets.getSheet("组织");
        List<OrgInfoExcelColumnVO> orgInfo = excelUtils.getBeanListFromExcelTwo(sheetOrg, OrgInfoExcelColumnVO.class);
        orgInfo = filterAllNull(orgInfo);
        // 数据处理
        orgInfo = Conditional.ofEmptyAble(orgInfo).orElse(new ArrayList<>()).stream().filter(x -> StringUtils.isNotBlank(x.getBusinessCode())).peek(x -> {
            if (StringUtils.isEmpty(x.getParentBusinessCode()) && !defaultBusinessCode.equalsIgnoreCase(x.getBusinessCode())) {
                x.setParentBusinessCode(defaultBusinessCode);
            }
            if (StringUtils.isEmpty(x.getBusinessCode())) {
                x.setBusinessCode(x.getOrgId());
            }
        }).collect(Collectors.toList());
        return orgInfo;
    }

    private List<OrgContactExcelColumnVO> getOrgContanctInfoExcelColumnVOS(XSSFWorkbook sheets) {
        XSSFSheet sheetInvoice = sheets.getSheet("联系");
        List<OrgContactExcelColumnVO> orgInvoice = excelUtils.getBeanListFromExcel(sheetInvoice, OrgContactExcelColumnVO.class);
        log.info("联系人信息：{}", JsonUtils.toJsonString(orgInvoice));
        return orgInvoice;
    }

    private List<OrgInvoiceInfoExcelColumnVO> getOrgInvoiceInfoExcelColumnVOS(XSSFWorkbook sheets) {
        XSSFSheet sheetInvoice = sheets.getSheet("发票");
        List<OrgInvoiceInfoExcelColumnVO> orgInvoice = excelUtils.getBeanListFromExcel(sheetInvoice, OrgInvoiceInfoExcelColumnVO.class);
        log.info("发票信息：{}", JsonUtils.toJsonString(orgInvoice));
        return orgInvoice;
    }


    private List<OrgDeliveryInfoExcelColumnVO> getOrgDeliveryInfoExcelColumnVOS(XSSFWorkbook sheets) {
        XSSFSheet sheetDelivery = sheets.getSheet("配送");
        List<OrgDeliveryInfoExcelColumnVO> orgDelivery = excelUtils.getBeanListFromExcel(sheetDelivery, OrgDeliveryInfoExcelColumnVO.class);
        log.info("配送信息：{}", JsonUtils.toJsonString(orgDelivery));
        return orgDelivery;
    }

    private List<OrgConfigExcelColumnVO> getOrgConfigExcelColumnVOS(XSSFWorkbook sheets) {
        XSSFSheet sheetOrgConfig = sheets.getSheet("组织设置");
        List<OrgConfigExcelColumnVO> orgConfigExcelColumnVOList = excelUtils.getBeanListFromExcel(sheetOrgConfig, OrgConfigExcelColumnVO.class);
        log.info("组织设置：{}", JsonUtils.toJsonString(orgConfigExcelColumnVOList));
        return orgConfigExcelColumnVOList;
    }

    private List<PayTypeConfigExcelColumnVO> getPayTypeConfigExcelColumnVOS(XSSFWorkbook sheets) {
        XSSFSheet sheetPayConfig = sheets.getSheet("支付设置");
        List<PayTypeConfigExcelColumnVO> payTypeColumnList =
                excelUtils.getBeanListFromExcel(sheetPayConfig, PayTypeConfigExcelColumnVO.class);
        log.info("支付设置：{}", JsonUtils.toJsonString(payTypeColumnList));
        return payTypeColumnList;
    }

    private  void extractContacts(Map<String, List<OrgContactExcelColumnVO>> mapOrgContacts, OrgInfoExcelColumnVO org, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp) {
        if (MapUtils.isNotEmpty(mapOrgContacts)) {
            List<OrgContactExcelColumnVO> listOrgContacts = mapOrgContacts.get(org.getBusinessCode());
            if (CollectionUtils.isNotEmpty(listOrgContacts)) {
                OrgContactExcelColumnVO oc = listOrgContacts.get(0);
                SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.ContactInfoEntity tempContact =
                        new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.ContactInfoEntity();
                tempContact.setContactName(oc.getContactName());
                tempContact.setContactEmail(oc.getContactEmail());
                if (StringUtils.isEmpty(oc.getContactCountryCode())) {
                    oc.setContactCountryCode(PhoneCountryCodeEnum.CN.getCountryCode());
                }
                if (StringUtils.isEmpty(oc.getContactCountryCode())) {
                    tempContact.setContactCountryCode(PhoneCountryCodeEnum.CN.getCountryCode());
                } else {
                    int contryCode = oc.getContactCountryCode().indexOf("+");
                    tempContact.setContactCountryCode(contryCode>-1? oc.getContactCountryCode().substring(contryCode):"+86");
                }
                tempContact.setContactPhone(oc.getContactPhone());
                tempContact.setLineNo(oc.getLineNo());
                tempContact.setMainLineNo(temp.getLineNo());
                temp.setContactInfo(tempContact);
            }
        }
    }

    private  void extractInvoice(Map<String, List<OrgInvoiceInfoExcelColumnVO>> mapOrgInvoice, OrgInfoExcelColumnVO org, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp) {
        if (MapUtils.isNotEmpty(mapOrgInvoice)) {
            List<OrgInvoiceInfoExcelColumnVO> listOrgInvoice = mapOrgInvoice.get(org.getBusinessCode());
            if (CollectionUtils.isNotEmpty(listOrgInvoice)) {
                temp.setInvoiceList(listOrgInvoice.stream().filter(Objects::nonNull).map(oi -> {
                    SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.InvoiceInfoEntity tempInvoice =
                            new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.InvoiceInfoEntity();
                    tempInvoice.setInvoiceTitle(oi.getInvoiceTitle());
                    tempInvoice.setTaxId(oi.getTaxId());
                    tempInvoice.setAccountBank(oi.getAccountBank());
                    tempInvoice.setAccountCardNo(oi.getAccountCardNo());
                    tempInvoice.setCorporationPhone(oi.getCorporationPhone());
                    tempInvoice.setCorporationAddress(oi.getCorporationAddress());
                    tempInvoice.setMainLineNo(org.getLineNo());
                    tempInvoice.setLineNo(oi.getLineNo());
                    return tempInvoice;
                }).collect(Collectors.toList()));
            }
        }
    }

    private  void extractDelivery(Map<String, List<OrgDeliveryInfoExcelColumnVO>> mapOrgDelivery, OrgInfoExcelColumnVO org, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp) {
        if (MapUtils.isNotEmpty(mapOrgDelivery)) {
            List<OrgDeliveryInfoExcelColumnVO> listOrgDelivery = mapOrgDelivery.get(org.getBusinessCode());
            if (CollectionUtils.isNotEmpty(listOrgDelivery)) {
                temp.setDeliveryAddressList(listOrgDelivery.stream().filter(Objects::nonNull).map(od -> {
                    SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.DeliveryAddressEntity tempDelivery = new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.DeliveryAddressEntity();
                    tempDelivery.setProvinceName(od.getProvinceName());
                    tempDelivery.setCityName(od.getCityName());
                    tempDelivery.setDistrictName(od.getDistrictName());
                    tempDelivery.setAddress(od.getAddress());
                    tempDelivery.setPostCode(od.getPostCode());
                    tempDelivery.setRecipientName(od.getRecipientName());
                    if (StringUtils.isEmpty(od.getRecipientCountryCode())) {
                        od.setRecipientCountryCode(PhoneCountryCodeEnum.CN.getCountryCode());
                    }
                    tempDelivery.setRecipientCountryCode(od.getRecipientCountryCode().startsWith("+") ? od.getRecipientCountryCode() : "+" + od.getRecipientCountryCode());
                    tempDelivery.setRecipientPhone(od.getRecipientPhone());
                    tempDelivery.setIsDefault(CommonEnum.Y.getDesc().equals(od.getIsDefault()));
                    tempDelivery.setMainLineNo(org.getLineNo());
                    tempDelivery.setLineNo(od.getLineNo());
                    return tempDelivery;
                }).collect(Collectors.toList()));
            }
        }
    }

    private void extractOrgConfig(Map<String, List<OrgConfigExcelColumnVO>> mapOrgConfig, OrgInfoExcelColumnVO org, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp) {
        if (MapUtils.isNotEmpty(mapOrgConfig)) {
            List<OrgConfigExcelColumnVO> listOrgConfig = mapOrgConfig.get(org.getBusinessCode());
            if (CollectionUtils.isNotEmpty(listOrgConfig)) {
                temp.setOrgConfigEntityList(listOrgConfig.stream().filter(Objects::nonNull).map(od -> {
                    SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.OrgConfigEntity orgConfigEntity = new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.OrgConfigEntity();
                    orgConfigEntity.setBusinessCode(od.getBusinessCode());
                    orgConfigEntity.setProjectIsNeed(od.getProjectIsNeed());
                    orgConfigEntity.setCostCenterIsNeed(od.getCostCenterIsNeed());
                    orgConfigEntity.setLineNo(od.getLineNo());
                    orgConfigEntity.setMainLineNo(org.getLineNo());
                    return orgConfigEntity;
                }).collect(Collectors.toList()));
            }
        }
    }

    private void extractPayType(Map<String, List<PayTypeConfigExcelColumnVO>> mapPayType, OrgInfoExcelColumnVO org, SyncOrganizationRequestEntity.SyncOrganizationInfoEntity temp) {
        if (MapUtils.isNotEmpty(mapPayType)) {
            List<PayTypeConfigExcelColumnVO> listPayType = mapPayType.get(org.getBusinessCode());
            if (CollectionUtils.isNotEmpty(listPayType)) {
                temp.setPayTypeConfigList(listPayType.stream().filter(Objects::nonNull).map(od -> {
                    SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.PayTypeConfigEntity tempDelivery = new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.PayTypeConfigEntity();
                    tempDelivery.setCarPub(od.getCar());
                    tempDelivery.setBusinessCode(od.getBusinessCode());
                    tempDelivery.setHotelPub(od.getHotel());
                    tempDelivery.setFlightPub(od.getFlight());
                    tempDelivery.setFlightintlPub(od.getFlightintl());
                    tempDelivery.setHotelintlPub(od.getHotelintl());
                    tempDelivery.setTrainPub(od.getTrain());
                    tempDelivery.setMainLineNo(org.getLineNo());
                    tempDelivery.setLineNo(od.getLineNo());
                    return tempDelivery;
                }).collect(Collectors.toList()));
            }
        }
    }

    /**
     * 如果是部门且没有配送地址，使用父级的
     */
    private void handleDeliveryAddress(List<SyncOrganizationRequestEntity.SyncOrganizationInfoEntity> orgList,
                                       Map<String, List<OrgInfoExcelColumnVO>> mapOrgInfo,
                                       Map<String, List<OrgDeliveryInfoExcelColumnVO>> mapOrgDelivery) {
        if (CollectionUtils.isEmpty(orgList)) {
            return;
        }
        orgList.forEach(item -> {
            SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.BasicInfoEntity basicInfo = item.getBasicInfo();
            // 如果是部门没有配置配送地址 将公司配置的配送地址填补进来
            List<OrgDeliveryInfoExcelColumnVO> orgDeliveryInfoExcelColumnVOS =
                    mapOrgDelivery.get(basicInfo.getBusinessCode());
            if (OrgTypeEnum.D.getCode().equals(basicInfo.getType())
                    && (CollectionUtils.isEmpty(orgDeliveryInfoExcelColumnVOS)
                    || orgDeliveryInfoExcelColumnVOS.size() == 0)) {
                List<OrgDeliveryInfoExcelColumnVO> orgDeliveryInfoNew =
                        this.deliveryRecursion(mapOrgInfo, mapOrgDelivery, basicInfo.getParentOrgId());

                item.setDeliveryAddressList(orgDeliveryInfoNew.stream().filter(Objects::nonNull).map(od -> {
                    SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.DeliveryAddressEntity tempDelivery =
                            new SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.DeliveryAddressEntity();
                    tempDelivery.setProvinceName(od.getProvinceName());
                    tempDelivery.setCityName(od.getCityName());
                    tempDelivery.setDistrictName(od.getDistrictName());
                    tempDelivery.setAddress(od.getAddress());
                    tempDelivery.setPostCode(od.getPostCode());
                    tempDelivery.setRecipientName(od.getRecipientName());
                    if (StringUtils.isEmpty(od.getRecipientCountryCode())) {
                        od.setRecipientCountryCode(PhoneCountryCodeEnum.CN.getCountryCode());
                    }
                    tempDelivery.setRecipientCountryCode(od.getRecipientCountryCode().startsWith("+")
                            ? od.getRecipientCountryCode() : "+" + od.getRecipientCountryCode());
                    tempDelivery.setRecipientPhone(od.getRecipientPhone());
                    tempDelivery.setIsDefault(CommonEnum.Y.getDesc().equals(od.getIsDefault()));
                    return tempDelivery;
                }).collect(Collectors.toList()));
            }

        });

    }

    public List<OrgDeliveryInfoExcelColumnVO> deliveryRecursion(Map<String, List<OrgInfoExcelColumnVO>> mapOrgInfo, Map<String, List<OrgDeliveryInfoExcelColumnVO>> mapOrgDelivery, String orgId) {
        List<OrgInfoExcelColumnVO> orgInfoExcelColumnVOS = mapOrgInfo.get(orgId);
        if (CollectionUtils.isNotEmpty(orgInfoExcelColumnVOS) && orgInfoExcelColumnVOS.size() > 0) {
            OrgInfoExcelColumnVO orgInfoExcelColumnVO = orgInfoExcelColumnVOS.get(0);
            //公司
            if (OrgTypeEnum.C.getDesc().equals(orgInfoExcelColumnVO.getType())) {
                return CollectionUtils.isEmpty(mapOrgDelivery.get(orgInfoExcelColumnVO.getOrgId())) ? new ArrayList<>() : mapOrgDelivery.get(orgInfoExcelColumnVO.getOrgId());
            } else {
                return deliveryRecursion(mapOrgInfo, mapOrgDelivery, orgInfoExcelColumnVO.getParentOrgId());
            }
        } else {
            return new ArrayList<>();
        }
    }


    /**
     * 组织排序
     *
     * @param orgList
     * @return
     */
    private List<OrgInfoExcelColumnVO> sortOrgList(List<OrgInfoExcelColumnVO> orgList) {
        List<OrgInfoExcelColumnVO> sortedList = new ArrayList<>(orgList);
        List<OrgInfoExcelColumnVO> tempRemoveList = sortedList.stream().filter(x -> "Y".equals(x.getIsDelete())).collect(Collectors.toList());
        //保证先删除(子->父)，再添加(父->子)
        sortedList.removeAll(tempRemoveList);
        Collections.reverse(tempRemoveList);
        sortedList.addAll(0, tempRemoveList);
        return sortedList;
    }

    private List<OrgInfoExcelColumnVO> filterAllNull(List<OrgInfoExcelColumnVO> orgInfo) {
        List<OrgInfoExcelColumnVO> newOrgInfos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orgInfo)) {
            for (OrgInfoExcelColumnVO vo : orgInfo) {
                boolean exists = false;
                Field[] declaredField = vo.getClass().getDeclaredFields();
                for (Field field:declaredField){
                    field.setAccessible(true);
                    Object obj = null;
                    try {
                        obj = field.get(vo);
                    } catch (IllegalAccessException e) {
                        log.error("解析excel报错",e);
                        e.printStackTrace();
                    }
                    if (Objects.nonNull(obj) && !"lineNo".equals(field.getName())){
                        exists = true;
                    }
                }
                if (!exists){
                    continue;
                }
                newOrgInfos.add(vo);
            }
        }
        return newOrgInfos;
    }
}
